package com.roads.supervisor.controller;

import com.roads.common.annotation.Log;
import com.roads.common.constant.Constants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.page.TableDataInfo;
import com.roads.common.enums.BusinessType;
import com.roads.common.utils.StringUtils;
import com.roads.project.domain.ProInstitutionDetail;
import com.roads.project.service.IProInstitutionService;
import com.roads.supervisor.domain.SupBoqTemplate;
import com.roads.supervisor.domain.SupPeriod;
import com.roads.supervisor.service.ISupBoqTemplateService;
import com.roads.supervisor.service.ISupPeriodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 监理工期Controller
 *
 * @author nhp
 * @date 2022-07-07
 */
@RestController
@RequestMapping("/supervisor/period")
public class SupPeriodController extends BaseController {

    @Autowired
    private ISupPeriodService service;

    @Autowired
    private IProInstitutionService institutionService;

    @Autowired
    private ISupBoqTemplateService boqTemplateService;

    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('supervisor:period:list')")
    @GetMapping("/list")
    public TableDataInfo list(SupPeriod model) {
        startPage();
        List<SupPeriod> list = service.selectModelList(model);
        return getDataTable(list);
    }

    @PostMapping("/selectPeriodList")
    public AjaxResult selectPeriodList(String institutionCode) {
        SupPeriod search = new SupPeriod();
        search.setInstitutionCode(institutionCode);
        List<SupPeriod> list = service.selectModelList(search);
        return AjaxResult.success(list);
    }

    /**
     * 汇总功能工期下拉框
     *
     * @param institutionCode 标段编号
     * @return 结果
     */
    @PostMapping("/dropDownSummaryPeriodList")
    public AjaxResult dropDownSummaryPeriodList(String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        SupPeriod search = new SupPeriod();
        search.setInstitutionCode(institutionCode);
        List<SupPeriod> list = service.selectModelList(search);
        ajaxResult.put("periods", list);
        if (list.size() > 0) {
            //获取当前计量期次
            SupPeriod currentPeriod = service.getCurrentPeriod(institutionCode);
            if (StringUtils.isNull(currentPeriod)) {
                ajaxResult.put("periodName", list.get(0).getPeriodName());
            } else {
                ajaxResult.put("periodName", currentPeriod.getPeriodName());
            }
        }
        return ajaxResult;
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('supervisor:period:query')")
    @GetMapping(value = "/{periodId}")
    public AjaxResult getInfo(@PathVariable("periodId") Long periodId) {
        AjaxResult ajaxResult = new AjaxResult();
        SupPeriod period = service.getModelById(periodId);
        ajaxResult.put("period", period);
        // 查询清单模板
        SupBoqTemplate search = new SupBoqTemplate();
        search.setInstitutionCode(period.getInstitutionCode());
        List<SupBoqTemplate> templates = boqTemplateService.selectModelList(search);
        ajaxResult.put("templates", templates);
        return ajaxResult;
    }

    /**
     * 查询标段详情
     *
     * @param institutionCode 标段编号
     * @return 标段详情
     */
    @PostMapping("/getInstitutionDetail")
    public AjaxResult getInstitutionDetail(String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        ProInstitutionDetail detail = institutionService.getDetailModelByInnerCode(institutionCode);
        ajaxResult.put("beginDate", detail.getBeginDate());
        ajaxResult.put("endDate", detail.getEndDate());
        if (Constants.YES.equals(detail.getIsNaturalMonth())) {
            ajaxResult.put("businessReportingDate", "自然月");
        } else {
            ajaxResult.put("businessReportingDate", detail.getBusinessReportingDate());
        }
        return ajaxResult;
    }

    /**
     * 生成
     */
    @PreAuthorize("@ss.hasPermi('supervisor:period:gen')")
    @Log(title = "监理工期", businessType = BusinessType.GEN)
    @PostMapping("/gen")
    public AjaxResult gen(String institutionCode) {
        ProInstitutionDetail detail = institutionService.getDetailModelByInnerCode(institutionCode);
        String result = validateInstitution(detail);
        if (StringUtils.isNotEmpty(result)) {
            return error(result);
        }
        // 已计量不能进行生成操作
        return toAjax(service.gen(detail, getUsername()));
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('supervisor:period:add')")
    @Log(title = "监理工期", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(String institutionCode) {
        ProInstitutionDetail detail = institutionService.getDetailModelByInnerCode(institutionCode);
        String result = validateInstitution(detail);
        if (StringUtils.isNotEmpty(result)) {
            return error(result);
        }
        return toAjax(service.insert(detail, getUsername()));
    }


    /**
     * 验证标段是否存在，标段开始日期，截止日期是否为空
     *
     * @param detail 标段编码
     * @return 结果
     */
    private String validateInstitution(ProInstitutionDetail detail) {
        if (null == detail) {
            return "生成标段工期失败，未找到相对应的标段";
        }
        if (null == detail.getBeginDate()) {
            return "生成标段工期失败，标段开始时间为空";
        }
        if (null == detail.getEndDate()) {
            return "生成标段工期失败，标段截止时间为空";
        }
        return "";
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('supervisor:period:edit')")
    @Log(title = "监理工期", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SupPeriod model) {
        return toAjax(service.update(model));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('supervisor:period:remove')")
    @Log(title = "监理工期", businessType = BusinessType.DELETE)
    @DeleteMapping
    public AjaxResult remove(String institutionCode) {
        SupPeriod lastPeriod = service.getLastPeriod(institutionCode);
        if (lastPeriod == null) {
            return error("删除失败，该标段未创建工期");
        }
        return toAjax(service.delete(lastPeriod.getPeriodId()));
    }

    /**
     * 报表列表工期下拉框
     *
     * @param institutionCode 标段编号
     * @return 结果
     */
    @PostMapping("/dropDownReportPeriodList")
    public AjaxResult dropDownReportPeriodList(String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        SupPeriod search = new SupPeriod();
        search.setInstitutionCode(institutionCode);
        List<SupPeriod> list = service.selectModelList(search);
        ajaxResult.put("periods", list);
        if (list.size() > 0) {
            //获取当前计量期次
            SupPeriod currentPeriod = service.getCurrentPeriod(institutionCode);
            if (StringUtils.isNull(currentPeriod)) {
                ajaxResult.put("periodName", list.get(0).getPeriodName());
            } else {
                ajaxResult.put("periodName", currentPeriod.getPeriodName());
            }
        }
        return ajaxResult;
    }

}
